On this page

Skip to content

ASP.NET Core Web API Getting Started Notes

TLDR

  • ControllerBase is suitable for pure Web API development; inherit from Controller if View support or Filter events are required.
  • [ApiController] provides automated behaviors such as attribute routing, automatic HTTP 400 responses, and parameter binding inference.
  • It is recommended to use ActionResult<T> as the Action return type to balance data return and status code control.
  • For routing configuration, it is recommended to use the [Route] attribute and explicitly specify verbs like [HttpGet], [HttpPost], etc.
  • When integrating Swagger, ensure every Action has an HTTP attribute; otherwise, the UI display may be abnormal.
  • You can use IOperationFilter to add custom fields (such as Tokens) in Swagger.
  • Enabling XML documentation comments can significantly improve the quality of Swagger documentation; you need to set GenerateDocumentationFile in the .csproj file.

Project Creation and Basic Configuration

When creating a Web API project in Visual Studio, consider the following:

  • Enable OpenAPI support: Checking this will automatically install Swashbuckle.AspNetCore and configure Swagger.
  • Top-level statements: A C# 9.0 feature that simplifies the Program.cs structure by removing the traditional Program class and Main method.
  • Use controllers: If unchecked, "Minimal APIs" will be created, which is suitable for lightweight services.

Controller and ApiController Explanation

Differences between ControllerBase and Controller

When to encounter this: When you need to decide the base class for your Controller.

  • ControllerBase: The default base class for Web API, which does not include View-related functionality.
  • Controller: Inherits from ControllerBase and provides additional View support and Filter events like OnActionExecuting. If you need to support both Views and APIs, it is recommended to inherit from this class.

ApiController Behavior

When to encounter this: When you want to simplify API validation and parameter binding logic. After marking with [ApiController], the system automatically enables the following features:

  • Attribute routing requirement.
  • Automatic HTTP 400 responses (automatic ModelState check).
  • Binding source parameter inference (e.g., [FromBody], [FromQuery], etc.).
  • Multipart/form-data request inference.
  • Problem details for error status codes.

If you need to disable some behaviors, you can adjust them via ConfigureApiBehaviorOptions in AddControllers() within Program.cs.

Routing and Parameter Binding

Attribute Routing

When to encounter this: When you need to define RESTful style or custom API paths. ASP.NET Core uses the [Route] attribute for routing configuration. The priority from high to low is: Action > Controller > Base Class.

TIP

  • After setting [ApiController], conventional routing (such as routes defined by UseEndpoints) will be disabled.
  • Use square brackets [] for route parameters (e.g., [controller]), rather than the curly braces {} used in conventional routing.

Parameter Binding Inference

When to encounter this: When you need to explicitly specify the parameter source. The system automatically infers the source based on the type:

  • [FromBody]: Complex types.
  • [FromForm]: IFormFile or IFormFileCollection.
  • [FromRoute]: Parameters matching the route template.
  • [FromQuery]: Other parameters.

Return Type Recommendations

When to encounter this: When you need to standardize the return format of your API. It is recommended to prioritize ActionResult<T>, as it allows developers to return both data and HTTP status codes, and it correctly displays the return type in Swagger documentation.

csharp
[HttpGet("{id}")]
public ActionResult<string> GetById(int? id) {
    if (!id.HasValue) {
        return BadRequest("Invalid id");
    }
    return $"GET method with id {id}";
}

Swagger Integration and Best Practices

Ensuring Swagger Works Correctly

When to encounter this: When your API cannot be correctly displayed or tested in the Swagger UI. Note: Even if an HTTP attribute is not explicitly set, the API defaults to a GET request. However, to ensure Swagger can correctly parse and display descriptions, be sure to explicitly mark each Action with an attribute like [HttpGet] or [HttpPost], and avoid designing public methods that are not intended as Actions.

Integrating XML Comments

When to encounter this: When you need your API documentation to include detailed parameter descriptions and examples.

  1. Add the following configuration to your .csproj:
xml
<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
  1. Add the XML path configuration in AddSwaggerGen within Program.cs:
csharp
builder.Services.AddSwaggerGen(opt => {
    string xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    opt.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});

Extending Swagger Functionality

When to encounter this: When you need to add global parameters (such as Tokens). You can implement the IOperationFilter interface and register it in AddSwaggerGen to add custom input fields to all API interfaces.

Change Log

  • 2023-08-04 Initial document creation.